package conn

import (
	myConfig "common/config"
	"common/helper"
	myredis "common/redis"
	myUserHelp "common/userHelp"
	"context"
	"crypto/sha256"
	"encoding/base64"
	"fmt"
	_ "github.com/go-sql-driver/mysql"
	"github.com/valyala/fasthttp"
	"golang.org/x/crypto/chacha20poly1305"
	"strconv"
)

var (
	xxteaKey = ""
	ctx      = context.Background()
)

func Use(xxKey string) {
	xxteaKey = xxKey
}

func Chacha20Encode(msg, pass string) string {

	key := sha256.Sum256([]byte(pass))
	aead, _ := chacha20poly1305.NewX(key[:])
	nonce := make([]byte, chacha20poly1305.NonceSizeX)

	return base64.StdEncoding.EncodeToString(aead.Seal(nil, nonce, []byte(msg), nil))
}

func Chacha20Decode(ciphertext, pass string) ([]byte, error) {

	decode, _ := base64.StdEncoding.DecodeString(ciphertext)
	key := sha256.Sum256([]byte(pass))
	aead, _ := chacha20poly1305.NewX(key[:])
	nonce := make([]byte, chacha20poly1305.NonceSizeX)

	return aead.Open(nil, nonce, decode, nil)
}
func SetSandbagRtp(Uid string, gameid string) {

	param := map[string]string{}
	param["uid"] = Uid
	param["gameid"] = gameid
	param["test"] = fmt.Sprintf("%d", myUserHelp.GetMemberTester(Uid))

	if myUserHelp.G_UserButton.IsSandbagState(Uid) {
		param["gtype"] = "12"
	} else {
		RtpControlWay := myUserHelp.G_UserButton.GetRtpControlWay(Uid)
		RtpControlWay = RtpControlWay % 10

		var fakepgRtp int = 0
		if RtpControlWay == 0 {
			sqlSelect := fmt.Sprintf("Select rtp FROM tbl_cfg_fake_rtp WHERE money<=%0.2f and game=100 and operator_id=%s	"+
				"order by money desc limit 1", myUserHelp.GetBalanceFloat64ByUid(Uid), myUserHelp.GetMemberOperatorId(Uid))
			err := myredis.GetMasterDBInstance().Get(&fakepgRtp, sqlSelect)
			if err != nil {
				if err.Error() != "sql: no rows in result set" {
					helper.SqlSelectErrLog(sqlSelect)
				}

				fakepgRtp = myConfig.GetOperatorInitRtp(myUserHelp.GetMemberOperatorId(Uid), helper.PG)
				if fakepgRtp == 0 {
					sqlSelect = fmt.Sprintf("Select rtp FROM tbl_cfg_fake_rtp WHERE money<=%0.2f and game=100 and operator_id=%s	"+
						"order by money desc limit 1", myUserHelp.GetBalanceFloat64ByUid(Uid), myConfig.Def_Channel)
					err = myredis.GetMasterDBInstance().Get(&fakepgRtp, sqlSelect)
					if err != nil {
						fakepgRtp = myConfig.GetOperatorInitRtp(myConfig.Def_Channel, helper.PG)
					}
				}
			}
		} else {
			fakepgRtp = myUserHelp.G_UserButton.GetFakePGRtp(Uid)
		}

		param["gtype"] = fmt.Sprintf("%d", fakepgRtp)
	}

	AdjustRtp, AdjustMoneyMul := myConfig.GetOperatorAdjustInfo(myUserHelp.GetMemberOperatorId(Uid), helper.PG)
	param["FakePgRTPMulti"] = strconv.Itoa(AdjustRtp)
	param["FakePgRTPValue"] = strconv.Itoa(AdjustMoneyMul)

	headers := map[string]string{
		"Content-Type": "application/json;charset=utf-8",
	}

	url := myConfig.GetGameCfgString(myConfig.CfgForwardingDomain)
	requestURI := url + "/pgggfake/index/setrtp"
	//fmt.Println(requestURI)
	content := fmt.Sprintf(`%s%s%s%s%s`, param["uid"], param["gtype"], param["gameid"], param["test"], "game_create_key_qwe123")
	sign := helper.MD5Hash(content)

	param["sign"] = sign
	requestParams, _ := helper.JsonMarshal(param)

	statusCode, body, err := HttpPostHeader(requestParams, requestURI, headers)

	if err != nil {
		helper.SqlSelectErrLog("requestURI:%s\nargs:%s\nbody:%s\n err:%s", requestURI, param, string(body), err.Error())
	}

	if statusCode != fasthttp.StatusOK {
		helper.SqlSelectErrLog("statusCode:%d", statusCode)
		helper.InfoLog("requestURI:%s args:%s body:%s", requestURI, param, string(body))
	}
}
